<?php

namespace App\Library\Service;

use App\Library\Logic\ShopCustomerImLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Logic\ShopUserMessageLogic;
use App\Library\Requests\Base\IdRequest;
use App\Library\Requests\Im\ImAddRequest;
use App\Library\Requests\Im\ImNewRequest;
use App\Library\Requests\Im\ImPageRequest;
use Illuminate\Http\JsonResponse;

class ImService extends BaseService
{
    /**
     * @param ShopCustomerImLogic $logic
     */
    public function __construct(ShopCustomerImLogic $logic)
    {
        $this->logic = $logic;
    }

    /**
     * 分页
     * @param ImPageRequest $request
     * @return JsonResponse
     */
    public function paging(ImPageRequest $request): JsonResponse
    {
        return success($this->logic->paging($request));
    }

    /**
     * 最新
     * @param ImNewRequest $request
     * @return JsonResponse
     */
    public function new(ImNewRequest $request): JsonResponse
    {
        return success($this->logic->new($request));
    }

    /**
     * 最新
     * @param ImAddRequest $request
     * @return JsonResponse
     */
    public function add(ImAddRequest $request): JsonResponse
    {
        if (is_null($request->text)) $text = null;
        else $text = htmlspecialchars(strip_tags(trim($request->text)));
        if (empty($text) && is_null($request->fileId)) return failMessage('内容不能为空');
        ShopUserMessageLogic::add(USERID, $request->acceptId, is_null($request->fileId) ? $text : '[图片]');
        ShopUserMessageLogic::add($request->acceptId, USERID, is_null($request->fileId) ? $text : '[图片]');
        return success($this->logic->insertForModel([
            'sendUserId' => USERID,
            'receiveUserId' => $request->acceptId,
            'ciIsImg' => is_null($request->fileId) ? 2 : 1,
            'ciContent' => $text,
            'ciContentImg' => $request->fileId,
            'ciAddTime' => time(),
            'createdAt' => time(),
            'updatedAt' => time(),
        ])->ci_id);
    }

    /**
     * userInfo
     * @param IdRequest $request
     * @return JsonResponse
     */
    public function userInfo(IdRequest $request): JsonResponse
    {
        return success(ShopUserLogic::query()->whereIn('user_id', [$request->id, USERID])
            ->get(['user_id', 'user_name', 'user_mobile', 'user_nickname', 'user_avatar']));
    }
}
